package com.yunhaikeji.core.poi;

import com.yunhaikeji.core.util.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cglib.beans.BeanMap;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class ListToExcel {
	
	private static final Logger log = LoggerFactory.getLogger(ListToExcel.class);
	
	public static void listToExcel(List<String> header, List<String> keys, List<Map<String, Object>> rows, Excel e){
		for (int i = 0; i < header.size(); i++) {
			e.setValue(0, i, header.get(i));
		}
		for (int row = 0; row < rows.size(); row++) {
			Map<String, Object> r = rows.get(row);
			for (int col = 0; col < keys.size(); col++) {
				Object value = r.get(keys.get(col));
				if (value instanceof Date) {
					value = DateUtils.formatDate((Date) value, "yyyy-MM-dd");
				}
				e.setValue(row + 1, col, value == null ? "" : value + "");
			}
		}
	}

	public static void listToExcel(List<KeyMap> keyMaps, List<?> objs, Excel e) {

		List<String> header = new ArrayList<>();
		List<String> keys = new ArrayList<>();
		List<Map<String, Object>> rows = new ArrayList<>();
		keyMaps.forEach(x -> {
			header.add(x.getLabel());
			keys.add(x.getName());
		});
		objs.forEach(x -> {
			rows.add(BeanMap.create(x));
		});
		listToExcel(header, keys, rows, e);
	}

}
